# import json
#
# from QQLoginTool.QQtool import OAuthQQ
# from django.conf import settings
# from django.contrib.auth import login
#
# from django.http import JsonResponse
# from django.shortcuts import render
#
# # Create your views here.
# from django.views import View
# import logging
#
# from django_redis import get_redis_connection
#
# from oauth.models import OAuthQQUser
# from oauth.utils import generate_access_token, check_access_token
# from users.models import User
#
# logger = logging.getLogger('django')
#
#
# class QQFirstView(View):
#     '''提供qq登录网页地址'''
#
#     def get(self, request):
#         # next 表示从哪个页面进入登录页面
#         # 登录成功后就自动返回那个页面
#         next = request.GET.get('next')
#         # 获取qq登录页面网址
#         # 创建OAuth类的对象
#         oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
#                         client_secret=settings.QQ_CLIENT_SECRET,
#                         redirect_uri=settings.QQ_REDIRECT_URI,
#                         state=next)
#         # 调用对象获取请求的地址的方法
#         login_url = oauth.get_qq_url()
#         return JsonResponse({'code': 0,
#                              'errmsg': 'ok',
#                              'login_url': login_url})
#
#
# class QQUserView(View):
#     '''用户扫码登录的回调处理'''
#
#     def get(self, request):
#         ' OAuth2.0认证 '
#         # 获取前端发送过来的code参数
#         code = request.GET.get('code')
#         if not code:
#             return JsonResponse({'code': 400,
#                                  'errmsg': '缺少必要参数'})
#
#         oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
#                         client_secret=settings.QQ_CLIENT_SECRET,
#                         redirect_uri=settings.QQ_REDIRECT_URI)
#         try:
#             access_token = oauth.get_access_token(code)
#             openid = oauth.get_access_token(access_token)
#         except Exception as e:
#             logger.error(e)
#             return JsonResponse({'code': 400,
#                                  'errmsg': '获取qq信息失败'})
#         try:
#             oauth_qq = OAuthQQUser.objects.get(openid=openid)
#         except Exception as e:
#             access_token = generate_access_token(openid)
#             return JsonResponse({'code': 300,
#                                  'errmsg': 'ok',
#                                  'access_token': access_token})
#
#         else:
#             user = oauth_qq.user
#             login(request, user)
#             response = JsonResponse({'code': 0,
#                                      'errmsg': 'ok'})
#             response.set_cookie('username',
#                                 user.username,
#                                 max_age=None)
#             return response
#
#     def post(self, request):
#         dict = json.load(request.body)
#         mobile = dict.get('mobile')
#         password = dict.get('password')
#         sms_code_client = dict.get('sms_code')
#         access_token = dict.get('access_toke')
#         if not all([mobile, password, sms_code_client, ]):
#             return JsonResponse({'code': 400,
#                                  'errmsg': '缺少必要参数'})
#         redis_conn = get_redis_connection('verify_code')
#         sms_code_server = redis_conn.get('sms %s' % mobile)
#         if sms_code_server is None:
#             return JsonResponse({'code': 400,
#                                  'errmsg': '验证码过期'})
#         if sms_code_client != sms_code_server.decode():
#             return JsonResponse({'code': 400,
#                                  'errmsg': '验证码输入错误'})
#         openid = check_access_token(access_token)
#         if not openid:
#             return JsonResponse({'code': 400,
#                                  'errmsg': '缺少openid'})
#         try:
#             user = User.objects.create_user(username=mobile,
#                                             mobile=mobile,
#                                             password=password)
#         except Exception as e:
#             return JsonResponse({'code': 400,
#                                  'errmsg': '往数据库添加数据错误'})
#         login(request, user)
#         response = JsonResponse({'code': 0,
#                                  'errmsg': 'ok'})
#         response.set_cookie('username',
#                             user.username,
#                             max_age=None)
#         return response
import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View
from django.conf import settings
from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
import logging

from oauth.utils import generate_access_token, check_access_token
from users.models import User

logger = logging.getLogger('django')


class QQFirstView(View):
    def get(self, request):
        next = request.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'login_url': login_url})


class QQUserView(View):
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必要参数'})
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_access_token(access_token)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})

        try:
            oauthqquser = OAuthQQUser.objects.get(openid=openid)

        except Exception as e:
            # openid不存在,返回加密的openid==>access_token
            access_token = generate_access_token(openid=openid)
            return JsonResponse({'code': 300,
                                 'errmsg': 'ok',
                                 'access_token': access_token})


        else:
            # openid已经存在
            # 保持登录,
            # 设置cookie返回
            user = oauthqquser.user
            login(request, user)
            response = JsonResponse({'code': 0,
                                     'errmsg': 'ok'})
            response.set_cookie('username',
                                user.username,
                                max_age=None)
            return response

    def post(self, request):
        dict = json.loads(request.body)
        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code_client = dict.get('sms_code')
        access_token = dict.get('access_token')

        if not all([mobile, password, sms_code_client, access_token]):
            return JsonResponse([{'code': 400,
                                  'errmsg': '缺少必要参数'}])
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse([{'code': 400,
                                  'errmsg': 'mobile格式有误'}])
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse([{'code': 400,
                                  'errmsg': 'password格式有误'}])
        # 对access解码成openid,与服务端的openid对比

        redis_conn = get_redis_connection('verify_code')

        try:
            sms_code_server = redis_conn.get('sms_%s' % mobile)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '无法访问数据库'})
        if sms_code_server is None:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码过期'})
        if sms_code_client != sms_code_client.dsecode():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码输入错误'})

        openid = check_access_token(access_token)
        if not openid:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少参数'})

        try:
            user = User.objects.create_user(mobile=mobile)
        except Exception as e:
            # 用户不存在,新建用户
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            # 用户名存在,检查密码
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                     'errmsg': '输入的密码有误'})
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '访问数据库失败'})

        login(request, user)
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username',
                            user.mobile,
                            max_age=None)
        return response
